﻿/*------------------------------------------------*/
/* style="text-transform:uppercase;"将文本框值转大写
 * ------------------------------------------------*/

#region 程序引用

using System;
using System.Web;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Security;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Security.Cryptography;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Xml;
using System.Net;
using System.Collections.Generic;


#endregion
/// <summary>
/// 辅助函数
/// </summary>
public static class NtHelp
{  
    public static readonly string regitCode = "GetCode";
    public static sdk.WebService sms = new sdk.WebService(); 
    /// <summary>
    /// 获取md5码
    /// </summary>
    /// <param name="source">待转换字符串</param>
    /// <returns>md5加密后的字符串</returns>
    public static string getMD5(string source)
    {
        string result = "";
        try
        {
            MD5 getmd5 = new MD5CryptoServiceProvider();
            byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(source));
            result = BitConverter.ToString(targetStr).Replace("-", "");
            return result;
        }
        catch (Exception)
        {
            return "0";
        }

    }
    public static readonly string strUseridFormat = "0000000";//7位

    public static decimal decimal_days_evyear = 365.2564M;
    public static readonly string reg_checkcode = "Ck_Code_1801";
    public static readonly string adminlogin_ckcode = "Admin_Ck_Code_2016";

    private static long being_day = -1;
    private static long modyday = 0;
    private static string showdatetimestr = "网站已运行：1天";
    public static string getShowRundays()
    {
        if (modyday < 1 || being_day < 1 || modyday != long.Parse(DateTime.Now.ToString("yyyyMMdd")) || being_day != BLL.SpeciallySql.getWebrunbegin_long())
        {
            string sret = BLL.SpeciallySql.getWebrundate();
            if (sret != null && sret.Length > 2)
            {
                showdatetimestr = sret;
                modyday = long.Parse(DateTime.Now.ToString("yyyyMMdd"));
                being_day = BLL.SpeciallySql.getWebrunbegin_long();
            }
        }
        return showdatetimestr;
    }
    //发送站内信
    public static bool setmsg(long userid, string title, string content)
    {
        bool flg = false;
        Model.SF_Message msg = new Model.SF_Message();
        msg.UserID = userid;
        msg.sendID = -1;
        msg.m_title = title;
        msg.m_cont = content;
        msg.i_type = 0;
        msg.sendTime = DateTime.Now;
        if (BLL.SF_Message.Add(msg) > 0)
        { flg = true; }
        return flg;
    }

    #region 生成验证码图片

    /// <summary>
    /// 生成验证码图片，保存session名称CheckCode1993
    /// </summary>
    public static void CreateCheckCodeImageSnCheckCode1993()
    {
        int number;
        string checkCode = string.Empty;

        //随机数种子
        Random randoms = new Random();

        for (int i = 0; i < 4; i++) //校验码长度为4
        {
            //随机的整数
            number = randoms.Next();

            //字符从0-9,A-Z中随机产生,对应的ASCII码分别为
            //48-57,65-90
            number = number % 36;
            if (number < 10)
            {
                number += 48;
            }
            else
            {
                number += 55;
            }
            checkCode += ((char)number).ToString();
        }

        //在session中保存校验码
        System.Web.HttpContext.Current.Session[reg_checkcode] = checkCode;

        //若校验码为空，则直接返回
        if (checkCode == null || checkCode.Trim() == String.Empty)
        {
            return;
        }
        //根据校验码的长度确定输出图片的长度
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(85, 30);//(int)Math.Ceiling(Convert.ToDouble(checkCode.Length * 15))
        //创建Graphics对象
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机数种子
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            //画图片的背景噪音线 10条
            //---------------------------------------------------
            for (int i = 0; i < 10; i++)
            {
                //噪音线起点坐标(x1,y1),终点坐标(x2,y2)
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                //用银色画出噪音线
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            //---------------------------------------------------
            //Brush b = Brushes.Silver;
            //g.FillRectangle(b, 0, 0, image.Width, image.Height);
            //---------------------以上两种任选其一------------------------------
            //输出图片中校验码的字体: 12号Arial,粗斜体
            Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic));

            //线性渐变画刷
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Black, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);

            //画图片的前景噪音点 50个
            for (int i = 0; i < 50; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Peru), 0, 0, image.Width - 1, image.Height - 1);

            //创建内存流用于输出图片
            using (MemoryStream ms = new MemoryStream())
            {
                //图片格式指定为png
                image.Save(ms, ImageFormat.Jpeg);
                //清除缓冲区流中的所有输出
                System.Web.HttpContext.Current.Response.ClearContent();
                //输出流的HTTP MIME类型设置为"image/Png"
                System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";
                //输出图片的二进制流
                System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
        }
        finally
        {
            //释放Bitmap对象和Graphics对象
            g.Dispose();
            image.Dispose();
        }
    }
    #endregion
    #region 邮箱相关
    public static string getEmailSmtp()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["MembServerEmailSmtp"].ConnectionString;
    }
    public static string getEmailLoginMail()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["MembServerEmailname"].ConnectionString;
    }
    public static string getEmailLoginPassword()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["MembServerEmailPass"].ConnectionString;
    }
    #endregion
    #region 邮件处理方法

    /// <summary>
    /// 邮件发送类
    /// </summary>
    public static class NetMail
    {
        /// <summary>
        /// 邮件发送方法
        /// </summary>
        /// <param name="SmtpUrl">Smtp服务器地址</param>
        /// <param name="LoginMail">发送方邮箱地址</param>
        /// <param name="LoginPassword">发送方密码</param>
        /// <param name="ToMail">接收方邮箱</param>
        /// <param name="Subject">邮件主题</param>
        /// <param name="Content">邮件内容</param>
        /// <returns>发送结果</returns>
        public static bool SendMailNoAttachment(string SmtpUrl, string LoginMail, string LoginPassword, string ToMail, string Subject, string Content)
        {
            try
            {
                //准备发送的设置
                System.Net.Mail.MailMessage NtMail = new System.Net.Mail.MailMessage(LoginMail, ToMail);
                NtMail.Subject = Subject;
                NtMail.Body = Content;
                NtMail.BodyEncoding = System.Text.Encoding.UTF8;
                NtMail.SubjectEncoding = System.Text.Encoding.UTF8;
                NtMail.IsBodyHtml = true;
                NtMail.Priority = System.Net.Mail.MailPriority.High;

                //配置发送
                System.Net.Mail.SmtpClient sct = new System.Net.Mail.SmtpClient();
                sct.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                sct.Host = SmtpUrl;
                sct.Credentials = new System.Net.NetworkCredential(LoginMail, LoginPassword);
                try
                {
                    sct.Send(NtMail);
                    return true;
                }
                catch
                {
                    return false;
                }

            }
            catch
            {
                return false;
            }
        }
    }
    private static readonly string strsmtp = getEmailSmtp();
    private static readonly string LoginMail = getEmailLoginMail();
    private static readonly string LoginPassword = getEmailLoginPassword();
    private static bool SendMailNoAttach(string strToMail, string Subject, string Content)
    {
        try
        {
            return NetMail.SendMailNoAttachment(strsmtp, LoginMail, LoginPassword, strToMail, Subject, Content);
        }
        catch
        {
            return false;
        }
    }
    #endregion
    #region 发送找回密码邮件
    public static bool SendGetMobPassMail(string strToMail, string username, string pass)
    {
        if (strToMail != null && username != null && pass != null && username.Length > 1 && strToMail.Length > 1 && pass.Length > 1)
        {
            try
            {
                string Content = "    " + username + "，您在[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "]，申请找回密码，您的密码重置为" + pass + "，请及时修改。----[米米彩票]（注意：本邮件是系统自动发送，请不要回复！！！）";
                return NetMail.SendMailNoAttachment(strsmtp, LoginMail, LoginPassword, strToMail, username + ",找回密码(系统自动发送，请不要回复)", Content);
            }
            catch
            {
                return false;
            }
        }
        return false;
    }
    #endregion 
    #region 截取标题
    public static string subtitle(string title, int length)
    {
        if (title != null && title.Length > length)
        {
            return title.Substring(0, length) + "...";
        }
        return title;
    }
    public static string subtitle(object obj, int length)
    {
        if (obj != null)
        {
            string title = obj.ToString();
            if (title != null && title.Length > length)
            {
                return title.Substring(0, length) + "...";
            }
            return title;
        }
        return "";
    }
    #endregion
    #region 折扣
    public static string getdiscountString(string old, string now)
    {
        try
        {
            decimal Dold = Convert.ToDecimal(old);
            decimal Dnow = Convert.ToDecimal(now);
            if (Dnow > Dold || Dnow == Dold)
            {
                return "无折扣";
            }
            else if (Dold == 0)
            {
                return "无折扣";
            }
            else
            {
                decimal dis = Math.Round(Math.Abs(Dnow * 100 / Dold));
                dis = dis / 10;
                return dis.ToString("####.#") + " 折";
            }
        }
        catch
        {
        }
        return "";
    }
    #endregion
    #region 金额格式
    public static string getmoneyString(string money)
    {
        try
        {
            return Convert.ToDecimal(money).ToString("#############0.00");
        }
        catch
        {

        }
        return money;
    }

    public static string getmoneyandf(string money)
    {
        try
        {
            if (money != null && money.Length > 0)
            {
                return "￥" + Convert.ToDecimal(money).ToString("#############0.00");
            }
        }
        catch
        {

        }
        return "---";
    }
    public static string getmoneyandf_del(string money)
    {
        try
        {
            if (money != null && money.Length > 0)
            {
                return "<br/><del>￥" + Convert.ToDecimal(money).ToString("#############0.00") + "</del>";
            }
        }
        catch
        {

        }
        return "";
    }
    public static string getintegral(string integral)
    {
        try
        {
            if (integral != null && integral.Length > 0)
            {
                return Convert.ToDecimal(integral).ToString("#############0.00");
            }
        }
        catch
        {

        }
        return "---";
    }
    #endregion

    /// <summary>
    /// 转换成手机号,转换失败时返回-1
    /// </summary>
    /// <param name="strmob"></param>
    /// <param name="mob"></param>
    /// <returns></returns>
    public static bool toTheMob(string strmob, out long mob)
    {
        mob = -1;
        if (strmob != null && strmob.Length > 0)
        {
            try
            {
                long convertmob = Convert.ToInt64(strmob);
                if (convertmob < 99900000000 && convertmob > -99900000000)
                {
                    mob = convertmob;
                    return true;
                }
            }
            catch
            {
                mob = -1;
                return false;
            }
        }
        mob = -1;
        return false;
    }
    public static string LongTo_per_String(long number)
    {
        return (number / 100).ToString("0") + "." + (number % 100).ToString("00");
    }
    //日期加上天数得到新日期
    public static DateTime tonewdatetime(DateTime ddate, int daynum)
    {
        return (ddate .AddDays(daynum));
    }
    public static string decimalTo_CW_String(decimal number)
    {
        string ret = number.ToString();
        int index = ret.IndexOf(".");
        if (index > 0)
        {
            return LongTo_CW_String(Convert.ToInt64(ret.Substring(0, index))) + ret.Substring(index);
        }
        return number.ToString();
    }
    public static string LongTo_CW_String(long number)
    {
        //如果是负数，取正
        bool bellowzero = false;
        if (number < 0)
        {
            bellowzero = true;
            number = -number;
        }
        StringBuilder sb = new StringBuilder(number + "");
        //根据数字的大小决定循环几次  
        int count = (sb.Length - 1) / 3;
        int mod = sb.Length % 3 == 0 ? 3 : sb.Length % 3;
        for (int i = 1; i <= count; i++)
        {
            sb.Insert(mod + 3 * (count - i), ",");
        }
        if (bellowzero)
        {
            sb.Insert(0, "-");
        }
        return sb.ToString();
    }
    public static string fenlong_To_CW_String(long value)
    {
        if (value < 100)
        {
            return "0." + value.ToString();
        }
        long dotlow = value % 100;
        long dotheight = value / 100;
        return LongTo_CW_String(dotheight) + "." + (dotlow.ToString("00"));
    }
    public static long long_everyone_max = 2000000;

    public static string Decimal_To_per_String(decimal per)
    {
        if (per == Math.Floor(per))
        {
            return Math.Floor(per).ToString();
        }
        else
        {
            return per.ToString("##################0.00");
        }
    }
    /// <summary>
    /// 显示时间差
    /// 例如：满标用时
    /// </summary>
    /// <param name="begin"></param>
    /// <param name="end"></param>
    /// <returns></returns>
    public static string getall_time_str(DateTime begin, DateTime end)
    {
        if (new DateTime().Equals(end) || new DateTime(1, 1, 1).Equals(end))
        {
            return "";
        }
        else if (new DateTime().Equals(begin) || new DateTime(1, 1, 1).Equals(begin))
        {
            return "";
        }
        else
        {
            TimeSpan span = end - begin;
            if (span != null)
            {

                StringBuilder sb = new StringBuilder();
                sb.Append(span.Days + "天");
                sb.Append(span.Hours + "小时");
                sb.Append(span.Minutes + "分");
                sb.Append(span.Seconds + "秒");
                return sb.ToString();
            }
        }
        return "";
    }
    public static string getCreateOrderNo(string userid)
    {
        if (userid != null && userid.Length > 0)
        {
            return BLL.TInsert_Max.CreateOrderid(userid);
        }
        return "";
    }
    public static decimal getmoney_decimal(long value)
    {
        string str = value.ToString();
        if (str.Length < 3)
        {
            return Convert.ToDecimal("0." + str);
        }
        else
        {
            return Convert.ToDecimal(str.Substring(0, str.Length - 2) + "." + str.Substring(str.Length - 2));
        }
    }

    public static string Create_rOrder(string orderno, string userid, long totalincld, string realmon, string Tid,string zqID)
    {
        if (userid != null && userid.Length > 0)
        {
            Model.CMember cm = BLL.CMember.GetModel(long.Parse(userid));
            if (cm != null && cm.uesrState > 0)
            {
                Model.SF_u_rorder model = new Model.SF_u_rorder();
                model.user_id = long.Parse(userid);
                model.orderno = orderno;
                model.ordertime = DateTime.Now.AddMinutes(1);
                model.i_state = 0;
                model.total = getmoney_decimal(totalincld);
                model.realmon = Convert.ToDecimal(realmon==""?0:Convert.ToDecimal(realmon));
                model.n_user_realname = cm.realname;
                if (Tid != "")
                {
                    
                   // model.yongtuid = Tid;
                    //更新还款计划人表的还款状态字段为审核中
                    //Model.SF_hk_jihuaren jihuaren = BLL.SF_hk_jihuaren.GetModel(Convert.ToInt64(Tid));
                    //jihuaren.i_state = 2;//还款中
                    //BLL.SF_hk_jihuaren.Update(jihuaren);
                }
                BLL.SF_u_rorder.Add(model);
                 
            }
        }
        return "";
    }
    public static string Update_rOrder(string orderno, int flg)
    {

        Model.SF_u_rorder model = BLL.SF_u_rorder.GetModelbyorder(orderno);
        Model.CMember userInfo = BLL.CMember.GetModel(model.user_id); 
        string mobile = userInfo.mob;
        model.instate = flg;//1成功 2 失败 

        BLL.SF_u_rorder.Update(model);

        Model.UsersAccount uacc = BLL.UsersAccount.GetModelByuser_id(model.user_id);
        //充值条件：充值用户账户不为空，充值成功，充值记录的yongtuid为空,确认状态为0未确认
        if (uacc != null && flg == 1 && model.i_state == 0)
        {
            //充值and债权装让
            //更新用户的账户
            uacc.czTotal = uacc.czTotal + model.realmon;
            uacc.total = uacc.total + model.realmon;
            //更新充值记录
            model.i_state = 1;
            model.verify_adminid = 1;
            model.verify_adminname = "系统确认成功充值后自动更新";
            model.verify_time = DateTime.Now;
            if (BLL.SF_u_rorder.Update(model) > 0)
            {
                if (BLL.UsersAccount.Update(uacc) > 0)
                { 
                    return "成功！";
                }

            }

        }
        return "失败";
    }

}